package cn.taobaoke.restful.util;

import cn.taobaoke.restful.exception.TBKException;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串工具类.
 * 转换的数据源来自于订单数据Excel文档.
 *
 * @author yangzuo
 * @since 2017-03-29.
 */
public class StringUtil {

    public static final String pattern = "yyyy-MM-dd HH:mm:ss";

    public static Date stringToDate(String dateString) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {
            Date date = sdf.parse(dateString);
            return date;
        } catch (ParseException e) {
            throw new TBKException("日期[" + dateString + "]格式转换错误");
        }
    }

    public static Integer stringToInteger(String intString) {
        String trimStr = org.springframework.util.StringUtils.trimWhitespace(intString);
        try {
            Double aDouble = Double.parseDouble(trimStr);
            Integer integer = aDouble.intValue();
            return integer;
        } catch (NumberFormatException e) {
            throw new TBKException("字符串["+intString+"]转换整型错误");
        }
    }

    public static Double stringToDouble(String doubleString) {
        String trimStr = org.springframework.util.StringUtils.trimWhitespace(doubleString);
        try {
            Double aDouble = Double.parseDouble(trimStr);
            return aDouble;
        } catch (NumberFormatException e) {
            throw new TBKException("字符串["+doubleString+"]转换浮点型错误");
        }
    }

    public static Double ratioStringToDouble(String string) {
        String[] tokens = string.split("%");

        if (tokens.length < 1) {
            throw new TBKException("字符串["+ string +"]格式错误");
        }

        String trimStr = org.springframework.util.StringUtils.trimWhitespace(tokens[0]);
        try {
            Double aDouble = Double.parseDouble(trimStr);
            return aDouble;
        } catch (NumberFormatException e) {
            throw new TBKException("字符串["+string+"]转换浮点型错误");
        }
    }


    public static boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if( !isNum.matches() ){
            return false;
        }
        return true;
    }

    public static boolean isUrlEncode(String content){


        return false;
    }
}
